//
//  DownLoadController.m
//  HuLaQuan
//
//  Created by liyan on 16/1/21.
//  Copyright © 2016年 yuwubao. All rights reserved.
//

#import "DownLoadController.h"
#import "DownloadCell.h"
//logic model
#import "FMDownloadEngine.h"

#import <SDWebImage/UIImageView+WebCache.h>

#import "RadioPlayerViewController.h"

@interface DownLoadController ()
{
    float _current;
}
//logic model
@property(nonatomic,strong)FMDownloadEngine *fmDownloadEngine;

@property (nonatomic,strong) NSTimer *timer;

//getUrl
@property(nonatomic,strong)NSString *kUrl;

@property(nonatomic,strong) NSMutableArray *dataSource;

@property(nonatomic,strong)UISlider *value;

//savePath
@property(nonatomic,strong)NSMutableArray *pathArray;

@property(nonatomic,strong)NSIndexPath *selectedIndexPath;

@property (nonatomic) BOOL isDownloading;

@end

@implementation DownLoadController
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}
-(FMDownloadEngine *)fmDownloadEngine
{
    //
    if (!_fmDownloadEngine) {
      
        _fmDownloadEngine = [[FMDownloadEngine alloc] init];
    }
    return _fmDownloadEngine;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getOfflineDownloadListFinish:) name:@"GetOfflineDownloadListFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(downloadFileFinish:) name:@"DownloadFileFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getDownloadFilePath:) name:@"GetDownloadFilePath" object:nil];
    //发送获取下载列表请求；
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.fmDownloadEngine getOfflineDownloadList];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DownloadFileFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetOfflineDownloadListFinish" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetDownloadFilePath" object:nil];
}
#pragma mark - Call Back
//call back
- (void)getOfflineDownloadListFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        //getData
        NSLog(@" calll back message dic %@",messageDic);
        if ([messageDic[@"result"] isKindOfClass:[NSArray class]]) {
            NSLog(@"%@",self.dataSource);
            if (self.dataSource.count> 0) {
                [self.dataSource removeAllObjects];
            }
            
            DownLoadModel *tempModel ;
            for (NSDictionary *dic in messageDic[@"result"] ) {
                tempModel = [DownLoadModel createUserWithUserInfoDictionary:dic];
                [self.dataSource addObject:tempModel];
            }
            
        }else{
            if (self.dataSource.count> 0) {
                [self.dataSource removeAllObjects];
            }
            DownLoadModel *tempModel = [DownLoadModel createUserWithUserInfoDictionary:messageDic[@"result"]];
            [self.dataSource addObject:tempModel];

        }
        NSLog(@"result %@",self.dataSource);
        [self.tableView reloadData];
    }
    else
    {
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
- (void)downloadFileFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        self.kUrl = [[messageDic objectForKey:@"result"]objectForKey:@"downloadUrl"];
        

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录
        
        
        NSString *pathFile = [documentsDirectory stringByAppendingPathComponent:[self.kUrl lastPathComponent]];
        
        
        //addPath
        [_pathArray addObject:pathFile];
        NSLog(@"~~~~~~~~pathArray%@",_pathArray);
        //progress
        [self.fmDownloadEngine downloadWithProgress:self.kUrl progress:^(float  prog) {
            _current = prog;
            dispatch_async(dispatch_get_main_queue(), ^{
                DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:self.selectedIndexPath];

                
               // cell.downloadOverTime.text =[NSString stringWithFormat:@"下载时间:"];
                cell.downloadProgress.progress  = prog;
                int proInt = prog * 100;
                cell.downloadPresentContent.text = [NSString stringWithFormat:@"%d%%",proInt];
                
                
            });
        }];
        
    }
    else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

-(void)getDownloadFilePath:(NSNotification *)notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        // NSLog(@"call back result %@",messageDic);
        NSString *pathFile = messageDic[@"result"];
        [_pathArray addObject:pathFile];
        NSLog(@"~~~~~~~~pathArray%@",_pathArray);
        
        self.isDownloading = NO;
        [self.tableView reloadRowsAtIndexPaths:@[self.selectedIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        
        
        //addPath
        
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"下载已经完成" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alert show];
//        DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:self.selectedIndexPath];
//        cell.downloadOverTime.hidden = YES;
//        cell.downloadPresentContent.hidden = YES;
//        cell.downloadProgress.hidden = YES;
//        cell.downloadButton.hidden = YES;
//        NSUserDefaults *savePath = [NSUserDefaults standardUserDefaults];
//        [savePath setObject:_pathArray forKey:@"savePath"];
        
    }
    else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

#pragma mark createView
-(void)setupUI
{
    self.title = @"节目下载";
    
    [self setupNavBackButton];
    
    _pathArray = [[NSMutableArray alloc] init];
    
    [self setupFooterForTableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadCell" bundle:nil] forCellReuseIdentifier:@"download"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.model = [self.dataSource objectAtIndex:indexPath.row];
    
    DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"download"];
    cell.dowmLoadTitle.text = self.model.downloadTitle;
    cell.downLoadContent.text = self.model.downloadContent;
    [cell.downLoadImage sd_setImageWithURL:[NSURL URLWithString:self.model.downloadImage] placeholderImage:[UIImage imageNamed:@""]];
    cell.downLoadTime.text =[NSString stringWithFormat:@"下载时间：%@",self.model.downloadTime];
    
    
    cell.downloadButton.tag = indexPath.row;
    [cell.downloadButton addTarget:self action:@selector(downloadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    cell.downloadOverTime.hidden = self.isDownloading? NO : YES;
    cell.downloadPresentContent.hidden = self.isDownloading? NO : YES;
    cell.downloadProgress.hidden = self.isDownloading? NO : YES;

    cell.downloadButton.hidden = [self.pathArray count] ? YES : NO;

   
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    RadioPlayerViewController *mediaPlayer = [[RadioPlayerViewController alloc]init];
//    mediaPlayer.getSavePath = self.pathArray;
    if ( 0 == [_pathArray count]) {
        NSLog(@"$$$$$$%@",_pathArray);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"还未开始下载，暂无数据" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
    UIStoryboard *storyBoardA = [UIStoryboard storyboardWithName:@"FMRadio" bundle:nil];
    RadioPlayerViewController *controller = (RadioPlayerViewController *)[storyBoardA instantiateViewControllerWithIdentifier:  @"RadioPlayerViewController"];
    
    controller.fromDownloadController = YES;
    controller.getSavePath = self.pathArray;
    
    [self.navigationController pushViewController:controller animated:YES];
    }
    
}
//button action
-(void)downloadButtonAction:(UIButton *)button
{
    
    self.selectedIndexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
    self.model = [self.dataSource objectAtIndex:button.tag];
    NSLog(@"ID:%@",self.model.downloadFileID);
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.fmDownloadEngine downloadFile:self.model.downloadFileID];
    
}
#pragma mark - Navigation
//-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
//{
//    if ([[segue identifier] isEqualToString:@"ShowRadioPlayerViewController"]) {
//        RadioPlayerViewController *radioPlayer = (RadioPlayerViewController *)[segue destinationViewController];
//        radioPlayer.getSavePath = self.pathArray;
//        NSLog(@"chuanzhi %@",radioPlayer.getSavePath);
//        return;
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
